package com.anjufang.service.system.impl;

import com.anjufang.entity.AdminMenu;
import com.anjufang.entity.AdminUser;
import com.anjufang.entity.AdminUserToken;
import com.anjufang.mapper.AdminMenuMapper;
import com.anjufang.mapper.AdminUserMapper;
import com.anjufang.service.system.ShiroService;
import com.anjufang.utils.constant.Constant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
public class ShiroServiceImpl implements ShiroService {

	@Autowired
	private AdminMenuMapper adminMenuMapper;
	@Autowired
	private AdminUserMapper adminUserMapper;
	
	@Override
    @Transactional
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            List<AdminMenu> menuList = adminMenuMapper.queryList(new HashMap<>());
            permsList = new ArrayList<>(menuList.size());
            for(AdminMenu menu : menuList){
            	permsList.add(menu.getUrl());
            }
        }else{
        	permsList = adminUserMapper.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.add(perms);
        }
        return permsSet;
    }

    @Override
    public AdminUserToken queryByToken(String token) {
        return new AdminUserToken().selectOne("token = {0}", token);
    }

    @Override
    public AdminUser queryUser(Long userId) {
        return adminUserMapper.selectById(userId);
    }

}
